﻿
// kux2mp4Dlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "kux2mp4.h"
#include "kux2mp4Dlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// Ckux2mp4Dlg 对话框



Ckux2mp4Dlg::Ckux2mp4Dlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_KUX2MP4_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void Ckux2mp4Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT_DIR, m_editDir);
	DDX_Control(pDX, IDC_BUTTON_DIR, m_btn_chooseDir);
	DDX_Control(pDX, IDC_LIS_FILE, m_listCtrlFile);
	DDX_Control(pDX, IDC_PROGRESS1, m_progress);
	DDX_Control(pDX, IDC_BUTTON_BEGIN, m_btn_begin);
	DDX_Control(pDX, IDC_CHECK_CHOOSE, m_checkAll);
}

BEGIN_MESSAGE_MAP(Ckux2mp4Dlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_DIR, &Ckux2mp4Dlg::OnBnClickedButtonDir)
	ON_BN_CLICKED(IDC_BUTTON_BEGIN, &Ckux2mp4Dlg::OnBnClickedButtonBegin)
	ON_BN_CLICKED(IDC_CHECK_CHOOSE, &Ckux2mp4Dlg::OnBnClickedCheckChoose)
END_MESSAGE_MAP()


// Ckux2mp4Dlg 消息处理程序

BOOL Ckux2mp4Dlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码

	initControl();

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void Ckux2mp4Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void Ckux2mp4Dlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR Ckux2mp4Dlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void Ckux2mp4Dlg::OnBnClickedButtonDir()
{
	// TODO: 在此添加控件通知处理程序代码

	TCHAR			szFolderPath[MAX_PATH] = { 0 };
	BROWSEINFO		sInfo;
	::ZeroMemory(&sInfo, sizeof(BROWSEINFO));
	sInfo.pidlRoot = 0;
	sInfo.lpszTitle = _T("请选择一个文件夹：");
	sInfo.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_EDITBOX;
	sInfo.lpfn = NULL;

	// 显示文件夹选择对话框
	LPITEMIDLIST lpidlBrowse = ::SHBrowseForFolder(&sInfo);
	if (lpidlBrowse != NULL)
	{
		// 取得文件夹名
		if (::SHGetPathFromIDList(lpidlBrowse, szFolderPath))
		{
			m_strDirPath = szFolderPath;
			m_editDir.SetWindowTextW(m_strDirPath);
		}
		else {
			AfxMessageBox(m_strDirPath + _T(" 无效的目录."));
		}
	}
	if (lpidlBrowse != NULL)
	{
		::CoTaskMemFree(lpidlBrowse);
	}

	loadFile();
	m_progress.SetPos(0);
}

void Ckux2mp4Dlg::initControl()
{
	DWORD dwStyle = m_listCtrlFile.GetExtendedStyle(); //获取当前扩展样式
	dwStyle |= LVS_EX_FULLROWSELECT; //选中某行使整行高亮（report风格时）
	dwStyle |= LVS_EX_GRIDLINES; //网格线（report风格时）
	dwStyle |= LVS_EX_CHECKBOXES;
	m_listCtrlFile.SetExtendedStyle(dwStyle); //设置扩展风格

	CRect rect;
	m_listCtrlFile.GetClientRect(rect);
	m_listCtrlFile.InsertColumn(0, L"选取", LVCFMT_LEFT, rect.Width() * 1 / 10);
	m_listCtrlFile.InsertColumn(1, L"索引", LVCFMT_LEFT, rect.Width() * 1 / 10);
	m_listCtrlFile.InsertColumn(2, L"状态", LVCFMT_LEFT, rect.Width() * 2 / 10);
	m_listCtrlFile.InsertColumn(3, L"文件名", LVCFMT_LEFT, rect.Width() * 6 / 10);

	m_checkAll.SetCheck(TRUE);
}

void Ckux2mp4Dlg::insertListCtrl()
{
	m_listCtrlFile.DeleteAllItems();
	CRect rect;
	m_listCtrlFile.GetClientRect(rect);
	m_listCtrlFile.InsertColumn(0, L"选取", LVCFMT_LEFT, rect.Width() * 1 / 10);
	m_listCtrlFile.InsertColumn(1, L"索引", LVCFMT_LEFT, rect.Width() * 1 / 10);
	m_listCtrlFile.InsertColumn(2, L"状态", LVCFMT_LEFT, rect.Width() * 2 / 10);
	m_listCtrlFile.InsertColumn(3, L"文件名", LVCFMT_LEFT, rect.Width() * 6 / 10);

	int nIndex = m_listCtrlFile.GetItemCount();
	for (auto & it : m_vstrFiles) {
		it.first = nIndex;

		m_listCtrlFile.InsertItem(nIndex, L"");

		m_listCtrlFile.SetCheck(nIndex, TRUE);
		CString strId;
		strId.Format(L"%d", nIndex + 1);
		m_listCtrlFile.SetItemText(nIndex, 1, strId);
		m_listCtrlFile.SetItemText(nIndex, 2, L"待转换");
		m_listCtrlFile.SetItemText(nIndex ++, 3, it.second);
	}
	//m_listCtrlFile.UpdateWindow();
}

void Ckux2mp4Dlg::enableWindow(BOOL bStatus)
{
	m_editDir.EnableWindow(bStatus);
	m_btn_chooseDir.EnableWindow(bStatus);
	m_btn_begin.EnableWindow(bStatus);
	m_checkAll.EnableWindow(bStatus);
}

void Ckux2mp4Dlg::setListCtrlCheckStatus(BOOL bStatus)
{
	int nIndex = m_listCtrlFile.GetItemCount();
	for (int i = 0; i < nIndex; i++) {
		m_listCtrlFile.SetCheck(i, bStatus);
	}
}

bool Ckux2mp4Dlg::loadFile()
{
	if (m_strDirPath.IsEmpty())
		return false;

	CString strFilepath = m_strDirPath + _T("\\");
	CString strFilename = _T("");
	CString strFullname = _T("");

	CFileFind find;
	BOOL bFind = find.FindFile(m_strDirPath + _T("\\*.kux"));
	if (!bFind) {
		AfxMessageBox(m_strDirPath + _T(" 未找到kux文件."));
		return false;
	}

	m_vstrFiles.clear();
	while (bFind)
	{
		bFind = find.FindNextFile();
		if (find.IsDots())
			continue;
		else {
			strFilename = find.GetFileName();
			strFullname = strFilepath + strFilename;
			m_vstrFiles.emplace_back(std::make_pair(0, strFilename));
		}
	}

	if (m_vstrFiles.size() > 0)
		insertListCtrl();

	return true;
}

#define TRANSCODE (L"/c %s\\ffmpeg.exe -y -i \"%s\" -c:v copy -c:a copy -threads 4 \"%s\"")
UINT Ckux2mp4Dlg::transcodingFile_TheradFunc(LPVOID lparam)
{
	Ckux2mp4Dlg* pDlg = (Ckux2mp4Dlg*)lparam;

	pDlg->enableWindow(FALSE);

	CString strPath;
	GetModuleFileName(NULL, strPath.GetBufferSetLength(MAX_PATH + 1), MAX_PATH);
	strPath.ReleaseBuffer();
	int nIndex = strPath.ReverseFind('\\');
	strPath = strPath.Left(nIndex);

	auto getFileName = [](const CString& strFileName) {
		int nPos = strFileName.ReverseFind('.');
		CString  strName = strFileName.Left(nPos); // 获取文件名  
		return strName;
	};

	auto getFileExtName = [](const CString& strFileName) {
		int nPos = strFileName.ReverseFind('.');
		CString  strExt = strFileName.Right(strFileName.GetLength() - nPos - 1);
		return strExt;
	};

	auto getChooseItem = [pDlg]() {
		int nNum = 0;
		int nCount = pDlg->m_listCtrlFile.GetItemCount();

		for (auto i = 0; i < nCount; i++) {
			if (pDlg->m_listCtrlFile.GetCheck(i))
				nNum++;
		}

		return nNum;
	};

	int nChooseNum = getChooseItem();
	if (nChooseNum <= 0) {
		AfxMessageBox(L"未选中任何选项.");
		return -1;
	}

	pDlg->m_progress.SetRange32(0, 100);
	int nPos = 0;
	CString strData, strSrc, strDest, strFileName;

	int nCount = pDlg->m_listCtrlFile.GetItemCount();
	for (int i = 0; i < nCount; i++) {
		if (!pDlg->m_listCtrlFile.GetCheck(i))
			continue;

		strFileName = pDlg->m_listCtrlFile.GetItemText(i, 3);
		pDlg->m_progress.SetPos(nPos);
		nPos += 100 / nChooseNum;

		if (L"kux" != getFileExtName(strFileName))
			continue;

		strSrc.Format(L"%s\\%s", pDlg->m_strDirPath, strFileName);
		strDest.Format(L"%s\\%s.mp4", pDlg->m_strDirPath, getFileName(strFileName));

		strData.Format(TRANSCODE, strPath, strSrc, strDest);

		pDlg->m_listCtrlFile.SetItemText(i, 2, L"转换中...");

		SHELLEXECUTEINFO ShExecInfo = { 0 };
		ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
		ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
		ShExecInfo.hwnd = NULL;
		ShExecInfo.lpVerb = NULL;
		ShExecInfo.lpFile = L"C:\\Windows\\System32\\cmd.exe";
		ShExecInfo.lpParameters = strData.GetBuffer();
		ShExecInfo.lpDirectory = NULL;
		ShExecInfo.nShow = SW_HIDE;
		ShExecInfo.hInstApp = NULL;

		ShellExecuteEx(&ShExecInfo);
		WaitForSingleObject(ShExecInfo.hProcess, INFINITE);

		strData = _T("");
		pDlg->m_listCtrlFile.SetItemText(i, 2, L"转换完成");
	}
	pDlg->m_progress.SetPos(100);

	pDlg->enableWindow(TRUE);
	return 0;
}


void Ckux2mp4Dlg::OnBnClickedButtonBegin()
{
	// TODO: 在此添加控件通知处理程序代码

	pThread = AfxBeginThread(transcodingFile_TheradFunc, (LPVOID)this);
}


void Ckux2mp4Dlg::OnBnClickedCheckChoose()
{
	// TODO: 在此添加控件通知处理程序代码
	BOOL bStatus = FALSE;
	if (m_checkAll.GetCheck())
		bStatus = TRUE;

	m_checkAll.SetCheck(bStatus);
	setListCtrlCheckStatus(bStatus);
}
